# -*- coding: UTF-8 -*-
import HttpClient
import urllib.parse
import os.path, hashlib, random, time ,math, sys, re

class tWeibo:
	def __init__(self, uin, passwd):
		self.uin = uin
		self.passwd = passwd.encode('utf-8')
		# cookieJar = os.path.abspath("cookies\\cookies_%s.txt" % uin)
		cookieJar = os.path.dirname(__file__) + ("\\cookies\\cookies_%s.txt" % uin)
		if os.path.exists(cookieJar) is not True:
			fp = open(cookieJar, 'w')
			cookies = "\n".join(['# Netscape HTTP Cookie File', '# http://www.netscape.com/newsref/std/cookie_spec.html', '# This is a generated file!  Do not edit.', '', ''])
			fp.write(cookies)
			fp.close()
		self.hc = HttpClient.HttpClient(cookieJar)
		self.userAgent = [
				'Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0', 
				'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17',
			]
	def setLastId(self, html):
		ptn = '<div class="newsBox" id="talkNew"></div><ul id="talkList" class="LC"><li id="(?P<lastId>\d+)" rel="(?P<lastR>)"'
		group = re.search(ptn, html, re.I)
		if group is None:
			self.lastId = 0
			self.lastR = math.floor(time.time() * 1000)
		else:
			match = group.groupdict()
			self.lastId = match['lastId']
			self.lastR = match['lastR']
	def login(self):
		response = self.hc.get('http://t.qq.com/')
		redirectURL = response.geturl()
		if redirectURL != 'http://t.qq.com/':
			self.homeUrl = redirectURL
			self.setLastId(response.data.decode('utf-8'))
			return 
		print('正在重新登入.............')
		self.checkVC()
		params = {
			'ptlang' : '2052',
			'u' : self.uin,
			'p' : self.p.upper(),
			'verifycode' : self.VC.upper(),
			'low_login_enable' : '1',
			'low_login_hour' : '720',
			'css' : 'http://imgcache.qq.com/ptcss/b4/wb/46000101/login1.css',
			'aid' : '46000101',
			'mibao_css' : 'm_weibo',
			'u1' : 'http://t.qq.com',
			'ptredirect' : '1',
			'h' : '1',
			'from_ui' : '1',
			'dumy' : '',
			'fp' : 'loginerroralert',
			'action' : '13-17-57917',
			'g' : '1',
			't' : '2',
			'dummy' : '',
			'js_type' : '2',
			'js_ver' : '10009',}
		query =  urllib.parse.urlencode(params)
		url = "http://ptlogin2.qq.com/login?" + query
		response = self.hc.get(url)
		responseContent = response.data.decode('utf-8')
		ptnCB = "ptuiCB\('([^']*)','([^']*)','([^']*)','([^']*)','([^']*)', '([^']*)'\);"
		match = re.search(ptnCB, responseContent)
		if match is None or '登录成功！' != match.group(5):
			print("返回信息：%s\n登入失败" ,responseContent)
			sys.exit()
		self.hc.set_cookie('ptui_loginuin', self.uin)
		self.hc.set_cookie('o_cookie', self.uin)
		self.hc.set_cookie('uin', 'o' + self.uin)
		self.hc.set_cookie('pgv_info', '')
		self.hc.set_cookie('mb_reg_from', '8')
		self.hc.set_cookie('wb_regf', '%3B0%3B%3Bmessage.t.qq.com%3B0')
		a = int(time.time()*1000)
		self.hc.set_cookie('ssid', "s" + str((math.floor(random.random() * 2147483647) * a) % 10000000000))
		d = (math.floor(math.fabs(random.random() - 1) * 2147483647) * a) % 10000000000
		self.hc.set_cookie('pgv_pvid', str(d))
		response = self.hc.get('http://t.qq.com/')
		self.homeUrl = response.geturl() 
		# print(response.data.decode('utf-8'))
		self.setLastId(response.data.decode('utf-8', 'ignore'))
	def checkVC(self):
		url = 'http://check.ptlogin2.qq.com/check?uin=%s&appid=46000101&r=%.17f' % (self.uin, random.random())
		response = self.hc.get(url)
		# ptui_checkVC('0','!Y8Y','\x00\x00\x00\x00\x4b\x23\x19\x5f');
		responseContent = response.data.decode('utf-8')
		match = re.search("^.+\('([^']+)','([^']+)'.+\);$", responseContent)
		if match.group(1) != '0':
			print(responseContent)
			print('需要输入验证码！')
			sys.exit()
		F = hashlib.md5(self.passwd).digest().decode('Latin-1')
		E = hashlib.md5(F.encode('Latin-1') + int(self.uin).to_bytes(8, byteorder='big')).hexdigest()
		D = hashlib.md5((E.upper() + match.group(2).upper()).encode('Latin-1')).hexdigest()
		self.p = D
		self.VC = match.group(2)
	def get(self, url, header={}):
		return self.hc.get(url, header)
	def post(self, url, data=None, headers={}):
		return self.hc.post(url, data, headers)
	def publish(self, content, pic=''):
		"""weibo publish
	
		发布微博
		"""
		currentTime = int(time.time()*1000)
		params = {
			'content' : content,
			'startTime' : currentTime - random.randint(10000, 30000),
			'endTime' :   currentTime,
			'countType' : '',
			'viewModel' : '',
			'attips' : '',
			'pic' : pic,
			'apiType' : '8',
			'pgv_ref' : 'web.base.master.talkBox.btnMyHome',
			'syncQzone' : '0',
			'syncQQSign' : '0',
		}
		header = {'Referer': 'http://api.t.qq.com/proxy.html', 'rf': self.homeUrl}
		response = self.hc.post('http://api.t.qq.com/old/publish.php', params, header)
		responseContent = response.data.decode('utf-8')
		# print(responseContent)
		return responseContent
	def uploadextpic(self, pic):
		# 通过URL提交图片
		params = {
			'sourcepic' : pic,
			'apiType' : '8',
			'apiHost' : 'http://api.t.qq.com',
			'_r' : int(time.time()*1000)
		}
		header = {'Referer': 'http://upload.t.qq.com/proxy.html', 'rf': self.homeUrl}
		response = self.hc.post('http://upload.t.qq.com/old/uploadextpic.php', params, header)
		responseContent = response.data.decode('utf-8')
		# print(responseContent)
		return responseContent
	def publishQun(self, wqid, content, pic='', cIsuse='0' ):
		"""weibo publish
	
		发布微群微博
		"""
		currentTime = int(time.time()*1000)
		params = {
			'content' : content,
			'startTime' : currentTime - random.randint(10000, 30000),
			'endTime' :   currentTime,
			'countType' : '',
			'viewModel' : '',
			'attips' : '',
			'pic' : pic,
			'apiType' : '1',
			'wqid' : wqid,
			'cIsuse' : cIsuse,
			'cflag' : '1',
			'syncQzone' : '0',
			'syncQQSign' : '0',
		}
		header = {'Referer': 'http://api.t.qq.com/proxy.html', 'rf': 'http://qun.t.qq.com/' + wqid}
		response = self.hc.post('http://api.t.qq.com/old/publish.php', params, header)
		responseContent = response.data.decode('utf-8')
		# print(responseContent)
		return responseContent
	def mywqs(self):
		ptn = '<p><a title="" href="/(?P<qid>\d+)" rel="\d+" target="_blank">(?P<title>.+?)</a></p>'
		response = self.get('http://qun.t.qq.com/mywqs.php')
		responseContent = response.data.decode('utf-8')
		wqs = []
		groups = re.finditer(ptn, responseContent)
		if groups is None:
			return None
		for group in groups:
			wqs.append(group.groupdict())
		return wqs
	def topMenuWQ(self):
		"""weibo topMenuWQ
			
		获取微群列表
		"""
		params = {
			'_' : str(math.floor(time.time() * 1000)),
			'apiHost' : 'http://api.t.qq.com',
			'apiType' : '8',
			'_r' : str(math.floor(time.time() * 1000) - random.randint(100,2000)),
		}
		header = { 'rf' : self.homeUrl, 'Referer' : 'http://api.t.qq.com/proxy.html',}
		query = urllib.parse.urlencode(params)
		response = self.hc.get('http://api.t.qq.com/asyn/topMenuWQ.php?' + query, header)
		responseContent = response.data.decode('utf-8')
		import json
		result = json.loads(responseContent.strip())
		wqs = []
		try:
			if result['result'] != 0:
				return None
			ptn = '<a target="_blank" title="(?P<title>[^"]+)" href="http://qun.t.qq.com/(?P<qid>\d+)" boss="btnNewMenuGroup\d+" class="app_name_txt">'
			groups = re.finditer(ptn, result['info'])
			if groups is None:
				return None
			# print(groups)
			# return None
			for group in groups:
				wqs.append(group.groupdict())
		except KeyError as ke:
			return None
		return wqs
	def addAttention(self, account):
		"""weibo addAttention
		
		添加关注
		"""
		url = 'http://api.t.qq.com/old/follow.php'
		params = {'u' : account,
			'veriCode' : '',
			'lieuId' : '',
			'apiType' : '8',
			'apiHost' : 'http://api.t.qq.com',
		}
		header = { 'rf' : 'http://t.qq.com/' + account, 'Referer' : 'http://api.t.qq.com/proxy.html',}
		response = self.hc.post(url, params, header)
		responseContent = response.data.decode('utf-8')
		# {result:0,msg:'成功',info:{myfollow:[0,0]},followTips:0}
		return responseContent.strip()
	def sendPrivateLetter(self, account, content):
		"""weibo sendPrivateLetter
	
		发私信
		"""
		currentTime = int(time.time() * 1000)
		params = {
			'content' : '@%s %s' % (account, content),
			'startTime' : currentTime - random.randint(15 * 1000, 30 * 1000),
			'endTime' :   currentTime,
			'countType' : '',
			'viewModel' : '',
			'attips' : '',
			'pic' : '',
			'pId' : '',
			'type' : '7',
			'apiType' : '8',
			'pgv_ref' : '',
			'syncQzone' : '0',
			'share' : '0',
			'syncQQSign' : '0',
		}
		header = {'Referer': 'http://api.t.qq.com/proxy.html', 'rf': self.homeUrl}
		response = self.hc.post('http://api.t.qq.com/old/publish.php', params, header)
		responseContent = response.data.decode('utf-8')
		return responseContent
	def newMsgCount(self):
		"""weibo newMsgCount
	
		获取最新微博信息
		"""
		currentTime = int(time.time()*1000)
		params = {
			'type' : '4,3,2,20,19,1,8,13,17',
			'r' : self.lastR,
			'atType' : '4',
			'id' : self.lastId,
			'time' : currentTime // 1000,
			'apiType' : '8',
			'apiHost' : 'http://api.t.qq.com',
			'_r' : currentTime, 
		}
		query = urllib.parse.urlencode(params)
		header = {'Referer': 'http://message.t.qq.com/proxy.html', 'rf': self.homeUrl}
		response = self.hc.get('http://message.t.qq.com/newMsgCount.php?' + query, header)
		responseContent = response.data.decode('utf-8')
		return responseContent
	def follow(self, accounts):
		"""weibo follow
	
		批量收听
		"""
		params = {
			'u' : ','.join(accounts),
			'veriCode':'',
			'lieuId':'',
			'apiType':'8',
			'apiHost':'http://api.t.qq.com',
		}
		header = {'Referer': 'http://api.t.qq.com/proxy.html', 'rf': 'http://zhaoren.t.qq.com/find/interest.php'}
		response = self.hc.post('http://api.t.qq.com/old/follow.php', params, header)
		responseContent = response.data.decode('utf-8')
		# print(responseContent)
		return responseContent
	def microFriend(self, start, province_view='0', city_view=''):
		"""weibo microFriend
	
		微交友
		"""
		params = {
			'sex' : '0',
			'age' : '0',
			'height' : '0',
			'degree' : '0',
			'nation_view' : '1',
			'province_view' : province_view,
			'city_view' : city_view,
		}
		header = {
			'Origin':'http://zhaoren.t.qq.com',
			'Referer':'http://zhaoren.t.qq.com/microFriends.php?' + urllib.parse.urlencode(params),
			'User-Agent':'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17',
		}
		
		params['start'] = str(start)
		params['apiType'] = '8'
		params['apiHost'] = 'http://api.t.qq.com'
		
		response = self.hc.post('http://zhaoren.t.qq.com/asyn/microFriends.php', params, header)
		responseContent = response.data.decode('utf-8')
		return responseContent
	def follower(self, user, page):
		"""weibo follower
	
		获取听众列表
		"""
		params = {
			'u':user,
			't':'0',
			'st':'1',
			'p':str(page),
			'apiType':'8',
			'apiHost':'http://api.t.qq.com',
			'_r' : int(time.time() * 1000),
		}
		header = {
			'Referer':'http://api.t.qq.com/proxy.html',
			'rf':'http://t.qq.com/%s/follower' % user,
			'User-Agent':self.userAgent[random.randint(0, len(self.userAgent) - 1)],
		}
		
		response = self.hc.get('http://api.t.qq.com/relations/follower.php?' + urllib.parse.urlencode(params), header)
		responseContent = response.data.decode('utf-8')
		return responseContent
	def getWeibo(self, page, timestamp=0, tid=0, user=None):
		if user is None:
			user = self.homeUrl.replace('http://t.qq.com/', '')
		params = {
			'u' : user,
			'apiType' : '8',
			'apiHost' : 'http://api.t.qq.com',
			'_r' : str(math.floor(time.time() * 1000)),
		}
		headers = {
			'Referer' : 'http://api1.t.qq.com/proxy.html',
			'rf' : 'http://t.qq.com/%s' % user,
			'User-Agent':self.userAgent[random.randint(0, len(self.userAgent) - 1)],
		}
		if page != 1:
			params['time'] = timestamp
			params['page'] = page
			params['id'] = tid
		response = self.hc.get('http://api1.t.qq.com/asyn/index.php?&' + urllib.parse.urlencode(params), headers)
		replacePtn = "{result:0,msg:'成功','info':{'user':'(?P<user>[^']+)','hasNext':1,'time':(?P<time>\d+),'talk':", '{"result":0,"msg":"成功","info":{"user":"\g<user>","hasNext":1,"time":\g<time>,"talk":'
		responseContent = re.sub(replacePtn, response.data.decode('utf-8').strip())
		return responseContent
	def pm_mgr(self, target, content):
		source = ['profile', 'home']
		params = {
			'source': source[random.randint(0, len(source) - 1)],
			'ptid':'',
			'roomid':'',
			'content' : content,
			'fid':'',
			'arturl':'',
			'murl':'',
			'target':target,
			'func':'send',
			'ef':'js',
			'pmlang':'zh_CN',
			'apiType':'8',
			'apiHost':'http://api.t.qq.com',
		}
		header = {
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			'Referer': 'http://api.t.qq.com/proxy.html?v=110321', 
			'User-Agent':self.userAgent[random.randint(0, len(self.userAgent) - 1)],
		}
		# self.hc.get('http://t.qq.com/' + target)
		response = self.hc.post('http://api.t.qq.com/inbox/pm_mgr.php', params, header)
		responseContent = response.data.decode('utf-8')
		# print(responseContent)
		return responseContent
	def userCard(self, account):
		params = {
			'u' : account,
			't' : '2',
			'apiType' : '8',
			'apiHost' : 'http://api.t.qq.com',
			'_r' : int(time.time() * 1000),
		}
		headers = {
			'Referer' : 'http://api1.t.qq.com/proxy.html',
			'rf' : self.homeUrl,
			'User-Agent':self.userAgent[random.randint(0, len(self.userAgent) - 1)],
		}
		return self.hc.get('http://api1.t.qq.com/asyn/userCard.php?' + urllib.parse.urlencode(params), headers) .data.decode('utf-8')
class tApp:
	def __init__(self, weibo, hc):
		self.httpClient = hc
		self.weibo = weibo
	def wenwen(self, content):
		return self.weibo.publish('#万能的微博#@问问 ' + content)